package com.xfly.app.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.base.PermissionListener;
import com.ptmall.app.bean.LocalFile;
import com.ptmall.app.bean.LocalImageHelper;
import com.ptmall.app.net.HttpMethods;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.net.okhttp.BusinessResponse;
import com.ptmall.app.net.okhttp.OkHttps;
import com.ptmall.app.ui.activity.LocalAlbumActivity;
import com.ptmall.app.ui.activity.ThActivity;
import com.ptmall.app.utils.AllUtils;
import com.ptmall.app.utils.FileUtils;
import com.ptmall.app.utils.GlideUtil;
import com.ptmall.app.utils.UriUtil;
import com.ptmall.app.view.GetPhotoPop;
import com.ptmall.app.view.TitleBarView;
import com.xfly.app.bean.LbBean;
import com.xfly.app.bean.UpBean;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AddLbActivity extends BaseMvpActivity implements View.OnClickListener, BusinessResponse {

    ImageView img, gimg;

    PopupWindow popupWindow;
    private View popView;

    private Uri cropImageUri;
    private Uri takePicUri;
    private final int CROP_IMG_WIDTH = 700;
    private final int CROP_IMG_HEIGHT = 700;

    private final int TAKE_PICTURE = 0x000001;
    private final int TAKE_PICTURES = 0x000002;

    private List<LocalFile> checkedItems = new ArrayList<>();
    private final int MAX_IMG_COUNT = 1;

    private String[] VIDEO_PERMISSION = {
            Manifest.permission.CAMERA,
            //Manifest.permission.RECORD_AUDIO,
            //Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    ApiDataRepository apiDataRepository = ApiDataRepository.getInstance();

    private TitleBarView title_bar;

    private LinearLayout selectgood, goodlin;

    String goodid = "";
    TextView name, price,btn;

    UpBean mUpBean1;
    private OkHttps okHttps;
    LbBean lbBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_lbsub);
    }

    @Override
    public void initViews() {
        lbBean = (LbBean) getIntent().getSerializableExtra("bean");
        img = findViewById(R.id.img);
        btn = findViewById(R.id.btn);
        title_bar = findViewById(R.id.title_bar);
        selectgood = findViewById(R.id.selectgood);
        goodlin = findViewById(R.id.goodlin);
        gimg = findViewById(R.id.gimg);
        name = findViewById(R.id.name);
        price = findViewById(R.id.price);
    }

    @Override
    public void initEvents() {
        okHttps = new OkHttps(this);
        okHttps.addResponseListener(this);
        title_bar.setText("轮播图管理");
        title_bar.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });
        selectgood.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), LbGoodActivity.class);
                startActivityForResult(intent, 4);
            }
        });
        goodlin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), LbGoodActivity.class);
                startActivityForResult(intent, 4);
            }
        });
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestRuntimePermisssions(VIDEO_PERMISSION, new PermissionListener() {
                    @Override
                    public void onGranted() {
                        pop();
                    }

                    @Override
                    public void onDenied(List<String> deniedList) {
                    }
                });
            }
        });
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addlb();
            }
        });

        if(lbBean!=null){
            goodid = lbBean.getGoods_id()+"";
            goodlin.setVisibility(View.VISIBLE);
            selectgood.setVisibility(View.GONE);
            name.setText(lbBean.getGoods_name());
            price.setText("￥" + lbBean.getGoods_price());
            GlideUtil.showImg(getContext(), lbBean.getGoods_cover(), gimg);
            GlideUtil.showImg(getContext(), lbBean.getCover(), img);
        }
    }

    private void pop() {
        if (null == popupWindow) {
            if (null == popView) {
                popView = LayoutInflater.from(this).inflate(R.layout.personaldata_pop, null);
                popView.findViewById(R.id.btn1).setOnClickListener(this);
                popView.findViewById(R.id.btn2).setOnClickListener(this);
                popView.findViewById(R.id.btn_cancel).setOnClickListener(this);
            }
//            View view = LayoutInflater.from(this).inflate(R.layout.personaldata_pop, null);
            popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            popupWindow.setAnimationStyle(R.style.dialogAnim);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    AllUtils.backgroundAlpha(1.0f, getWindow());
                }
            });
            //popupWindow.showAtLocation(rootView, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
        } else {
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn1://拍照
                takePicUri = getSomeUri();
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                openCameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, takePicUri);
                startActivityForResult(openCameraIntent, TAKE_PICTURE);
                popupWindow.dismiss();
                break;
            case R.id.btn2://本地相册
                Intent intent = new Intent(AddLbActivity.this,
                        LocalAlbumActivity.class);
                intent.putExtra("num", MAX_IMG_COUNT - checkedItems.size());
                startActivityForResult(intent, TAKE_PICTURES);
                popupWindow.dismiss();
                break;
            case R.id.btn_cancel:
                popupWindow.dismiss();
                break;

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PICTURE:
                if (resultCode == RESULT_OK) {
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    img.setImageBitmap(bm);
                    setImageToView(bm);
                    checkedItems.clear();
                }
                break;
            case TAKE_PICTURES:
                checkedItems.addAll(LocalImageHelper.getInstance().getCheckedItems());
                LocalImageHelper.getInstance().getCheckedItems().clear();
                if (checkedItems.size() > 0) {
                    Bitmap bm = checkedItems.get(0).getBitmap();
                    img.setImageBitmap(bm);
                    setImageToView(bm);
                }
                break;
            case 4:
                if (data != null) {
                    goodid = data.getStringExtra("id");
                    goodlin.setVisibility(View.VISIBLE);
                    selectgood.setVisibility(View.GONE);
                    name.setText(data.getStringExtra("name"));
                    price.setText("￥" + data.getStringExtra("price"));
                    GlideUtil.showImg(getContext(), data.getStringExtra("pic"), gimg);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 创建任一Uri
     *
     * @return
     */
    private Uri getSomeUri() {
        String fileName = FileUtils.SDPATH + String.valueOf(System.currentTimeMillis()) + ".jpg";
        String local = FileUtils.SDPATH;
        File folder = new File(local);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        return UriUtil.getFileUri(getContext(), new File(fileName));
    }


    protected void setImageToView(Bitmap data) {

        FileUtils.saveBitmap(data, "123456");
        okHttps.postAsynFile(HttpMethods.BASE_URL + "attachment/upload", new File(FileUtils.SDPATH + "123456.JPEG"), true, 1);
    }

    @Override
    public void OnMessageResponse(int id, String jo) {
        switch (id) {
            case 1:
                mUpBean1 = okHttps.getGson().fromJson(jo, new TypeToken<UpBean>() {
                }.getType());
                break;
        }
    }

    private void addlb() {
        Map<String, String> map = new HashMap<>();
        if (lbBean!=null) {
            map.put("slides_id", lbBean.getId()+"");
            if(TextUtils.isEmpty(goodid)){
                map.put("goods_id", lbBean.getGoods_id()+"");
            }else {
                map.put("goods_id", goodid);
            }
            if(mUpBean1!=null){
                map.put("cover", mUpBean1.getId()+"");
            }else {
                map.put("cover", lbBean.getCover_id()+"");
            }
            map.put("cover", lbBean.getCover_id()+"");
        }else {
            map.put("cover", mUpBean1.getId());
            map.put("goods_id", goodid);
        }
        apiDataRepository.bjaddlb(map, new ApiNetResponse<Object>() {
            @Override
            public void onSuccess(Object data) {
                showMsg("操作成功");
                finish();
            }
        });

    }

}
